
package com.gamatechno.solodestinationnew;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.view.CardGridView;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.gamatechno.solodestinationnew.entity.E_Location;
import com.gamatechno.solodestinationnew.helper.JSONHelper;
import com.gamatechno.solodestinationnew.utils.Utils;
import com.gamatechno.solodestinationnew.utils.Webservice;
import com.google.android.gms.maps.model.LatLng;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

public class CategoryActivity extends BaseActivity {

    private static final String TAG = "CATEGORY";

    private int category;
    private Bundle data;
    private String URL;
    private List<E_Location> listLocation;
    private List<Card> listCard;
    private LatLng location;
    private CardGridView cardGridView;
    private ProgressBar pBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);

        Utils.TRACE("CategoryActivity", "onCreate : ");

        overridePendingTransition(R.anim.activity_open_translate, R.anim.activity_close_scale);

        if (savedInstanceState == null) {
            Utils.TRACE("CategoryActivity", "onCreate : saveinstancestate null");
            data = getIntent().getExtras();
            if (data != null) {
                category = data.getInt("category");
                location = new LatLng(data.getDouble("lat"), data.getDouble("lng"));
            }
        } else {
            Utils.TRACE("CategoryActivity", "onCreate : get from save instance");
            category = savedInstanceState.getInt("category");
            location = new LatLng(savedInstanceState.getDouble("lat"),
                    savedInstanceState.getDouble("lng"));
        }

        listCard = new ArrayList<Card>();

        cardGridView = (CardGridView) findViewById(R.id.grid);
        pBar = (ProgressBar) findViewById(R.id.loader);

        switch (category) {
            case MainActivity.CATEGORY_KULINER:
                URL = Webservice.GET_KULINER(Utils.getDataStringFromSP(this, Utils.PREF_BAHASA));
                break;
            case MainActivity.CATEGORY_HOTEL:
                URL = Webservice.GET_HOTEL(Utils.getDataStringFromSP(this, Utils.PREF_BAHASA));
                break;
            case MainActivity.CATEGORY_TOURISM:
                URL = Webservice.GET_WISATA(Utils.getDataStringFromSP(this, Utils.PREF_BAHASA));
                break;
            case MainActivity.CATEGORY_SHOPPING:
                URL = Webservice.GET_SHOPPING(Utils.getDataStringFromSP(this, Utils.PREF_BAHASA));
                break;
            case MainActivity.CATEGORY_HANDYCRAFT:
                URL = Webservice.GET_HANDYCRAFT(Utils.getDataStringFromSP(this, Utils.PREF_BAHASA));
                break;
        }

        getData(URL);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Utils.TRACE("CategoryActivity", "onSaveInstanceState : ");
        outState.putInt("category", category);
        outState.putDouble("lat", location.latitude);
        outState.putDouble("lng", location.longitude);

    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        overridePendingTransition(R.anim.activity_open_scale, R.anim.activity_close_translate);
    }

    private void showLoading(boolean state) {
        cardGridView.setVisibility((state) ? View.GONE : View.VISIBLE);
        pBar.setVisibility((state) ? View.VISIBLE : View.GONE);
    }

    private void getData(String URL) {
        Utils.TRACE("CategoryActivity", "getData : " + URL);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
                URL,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject obj) {
                        showLoading(false);
                        Utils.TRACE("CategoryActivity.getData(...).new Listener() {...}",
                                "onResponse : " + obj.toString());
                        try {
                            if (obj.getInt("status") == 200) {
                                if (obj.getJSONArray("result").length() > 0) {
                                    listLocation = JSONHelper.getAllLocation(
                                            obj.getJSONArray("result"), category, location);
                                    initCard(listLocation);
                                }
                            }
                        } catch (JSONException e) {
                            Utils.TRACE("CategoryActivity", "getData : " + e.getMessage());
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        showLoading(false);
                        Utils.TRACE("CategoryActivity.getData(...).new ErrorListener() {...}",
                                "onErrorResponse : " + error.toString());
                        Utils.showVolleyError(CategoryActivity.this, error);
                    }
                });
        BaseApplication.getInstance().addToRequestQueue(request, TAG);
        showLoading(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        // getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_search) {
            startActivity(new Intent(this, SearchActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }

    private void initCard(List<E_Location> listLocation) {
        for (int i = 0; i < listLocation.size(); i++) {
            listCard.add(new CardLocation(this,
                    listLocation.get(i).getId(),
                    listLocation.get(i).getImgThumb(),
                    listLocation.get(i).getName(),
                    listLocation.get(i).getDesc(),
                    listLocation.get(i).getJarak(),
                    listLocation.get(i).getRate(),
                    listLocation.get(i).getLat(),
                    listLocation.get(i).getLng()
                    ));
        }

        CardArrayAdapter adapter = new CardArrayAdapter(this, listCard);
        cardGridView.setAdapter(adapter);
    }

    static class Holder {
        TextView title, distance;
        ImageView thumb;
        RatingBar rating;
        ProgressBar pBar;
    }

    private class CardLocation extends Card {
        private String gambar, title, desc;
        private float rate;
        private double jarak;
        private double lat, lng;

        public CardLocation(Context context, int id, String gambar, String title, String desc,
                double jarak,
                float rate, double lat, double lng) {
            super(context, R.layout.item_card_grid_category);
            setId("" + id);
            this.desc = desc;
            this.gambar = gambar;
            this.title = title;
            this.jarak = jarak;
            this.rate = rate;
            this.lat = lat;
            this.lng = lng;
            init();
        }

        private void init() {
            // TODO Auto-generated method stub
            setOnClickListener(new OnCardClickListener() {

                @Override
                public void onClick(Card card, View view) {
                    Bundle data = new Bundle();
                    data.putString("title", title);
                    data.putString("id", card.getId());
                    data.putString("img", gambar);
                    data.putString("desc", desc);
                    data.putDouble("distance", +jarak);
                    data.putFloat("rating", rate);
                    data.putDouble("lat", lat);
                    data.putDouble("lng", lng);
                    data.putInt("cat", category);

                    startActivity(new Intent(CategoryActivity.this, DetailLocationActivity.class)
                            .putExtras(data));
                }
            });
        }

        @Override
        public void setupInnerViewElements(ViewGroup parent, View view) {
            // super.setupInnerViewElements(parent, view);
            Holder holder = new Holder();

            holder.distance = (TextView) view.findViewById(R.id.txt_distance);
            holder.title = (TextView) view.findViewById(R.id.title_location);
            holder.rating = (RatingBar) view.findViewById(R.id.rating_category);

            final ImageView thumb = (ImageView)
                    view.findViewById(R.id.thumb_location);

            // TextView distance = (TextView)
            // view.findViewById(R.id.txt_distance);
            // TextView title = (TextView)
            // view.findViewById(R.id.title_location);
            // RatingBar rating = (RatingBar) view.findViewById(R.id.rating);
            final ProgressBar pBar = (ProgressBar)
                    view.findViewById(R.id.loader);

            ImageLoader.getInstance().displayImage(gambar, thumb,
                    BaseApplication.getDisplayImageOptions(),
                    new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                            // TODO Auto-generated method stub
                            super.onLoadingComplete(imageUri, view, loadedImage);
                            if (pBar != null) {
                                pBar.setVisibility(View.GONE);
                                thumb.setVisibility(View.VISIBLE);
                            }
                        }

                        @Override
                        public void onLoadingStarted(String imageUri, View view) {
                            super.onLoadingStarted(imageUri, view);
                            if (thumb != null)
                            {
                                thumb.setVisibility(View.GONE);
                                pBar.setVisibility(View.VISIBLE);
                            }
                        }
                    });

            holder.title.setText(this.title);
            holder.distance.setText(String.format("%.2f", jarak) + " km");
            holder.rating.setRating(rate);

        }
    }
}
